package com.zhxh.nzpos.query;

import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zhxh.nzpos.R;
import com.zhxh.nzpos.dao.LocalInfoDao;
import com.zhxh.nzpos.dao.SelloutDao;
import com.zhxh.nzpos.model.Buyin;
import com.zhxh.nzpos.model.LocalInfo;
import com.zhxh.nzpos.model.Sellout;
import com.zhxh.nzpos.model.Statistics;
import com.zhxh.nzpos.serialport.PrintSerialPort;
import com.zhxh.nzpos.utils.ViewUtil;

/**
 * 统计查询--订购查询
 * 
 * @author wangzt
 *
 */
public class QueryLevel2Activity extends PrintSerialPort {

	private ArrayList<Buyin> buyinItems;
	private SellOutLevle2QueryAdapter listAdapter;
	
	
	private String fromDate;
	private String toDate;
	private SimpleDateFormat simpleDateFormat;
	private SimpleDateFormat simpleDateFormat2;
	
	private SelloutDao selloutDao;
	LocalInfoDao dao;
	private ArrayList<Sellout> list;
	private Date btime;
	private Date etime;
	private Statistics statistics;
	private SendingThread mSendingThread;
	private String name;
	
	private TextView cate;
	private TextView date;
	private TextView sum;
	float total = 0f;

	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_buyin);
        selloutDao = new SelloutDao(this);
        dao = new LocalInfoDao(this);
        SharedPreferences sharedata = getSharedPreferences("PreferencesFile", 0);
        fromDate = sharedata.getString("btime", null);
		
        toDate = sharedata.getString("etime", null);
        
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
        try {
			btime = simpleDateFormat.parse(fromDate);
			etime = simpleDateFormat2.parse(toDate
					+ " 23:59:59");

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	Bundle b = getIntent().getExtras();
    	statistics = (Statistics) b.getSerializable("cate");
    	list = selloutDao.getScrollData(statistics.getId(), btime.getTime(), etime.getTime());
		
        
        initViews();
    }
	
	private void initViews() {
		
		cate = (TextView)findViewById(R.id.cate);
		cate.setText(statistics.getParent()+"-"+statistics.getName() +"   "+fromDate+"至"+toDate);
		//date = (TextView)findViewById(R.id.date);
		//date.setText(fromDate+"至"+toDate);
		
		sum = (TextView)findViewById(R.id.sum);
		
		List<LocalInfo> locals = dao.getAll();
		if (locals.size() > 0)
			name = locals.get(0).getName();
		ListView listView = (ListView) findViewById(R.id.query_listview);
	
		listAdapter = new SellOutLevle2QueryAdapter(getLayoutInflater(), list);
		listView.setAdapter(listAdapter);
		ImageView cancelBtn = (ImageView) findViewById(R.id.query_total);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (list.size() < 1) {
					ViewUtil.makeToast(getApplicationContext(), "请选择打印内容");
					return;
				}
				print();
			}
		});
		
		for (Sellout sellout :list) {
			total += sellout.getCount()*sellout.getPrice();

		}
		sum.setText("总计:"+total+"元");
		
	}
	private class SendingThread extends Thread {
		@Override
		public void run() {
			// while (!isInterrupted()) {
			try {
				if (mOutputStream != null) {
					onPrint(mOutputStream);
					return;
				} else {
					return;
				}
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			// }
		}
	}
	
	protected void onPrint(OutputStream mOutputStream) throws IOException {

		// TODO 按照格式补全打印信息

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

		mOutputStream.write("\r\n".getBytes());
		mOutputStream.write(("      大兴农资安全监管系统\r\n").getBytes("gbk"));
		mOutputStream.write(("        " + name + "\r\n").getBytes("gbk"));
		mOutputStream.write(("           销售统计打印\r\n").getBytes("gbk"));
		mOutputStream.write(("统计起始日期:" + fromDate + "\r\n").getBytes("gbk"));
		mOutputStream.write(("统计结束日期:" +toDate+ "\r\n").getBytes("gbk"));
		mOutputStream.write((statistics.getParent()+"-"+statistics.getName()+ "\r\n").getBytes("gbk"));
		mOutputStream.write("================================\r\n"
				.getBytes("gbk"));

		//Iterator<Statistics> iterator = map.keySet().iterator();
		//while (iterator.hasNext()) {
			//Statistics key = iterator.next();
			//System.out.println("map.get(key) is :" + map.get(key));
			mOutputStream.write("商品类别     数量   价格合计\r\n".getBytes("gbk"));
			
			//mOutputStream.write((key.getName() + "         "+key.getPrice().substring(0,key.getPrice().length()-1)+"\r\n").getBytes("gbk"));
			//ArrayList<Statistics> sells =  map.get(key);
			for (Sellout sellout :list) {
				//total += sellout.getCount()*sellout.getPrice();
				mOutputStream.write((sellout.getGoodsName() + "       \r\n").getBytes("gbk"));
				mOutputStream.write(("              "+sellout.getCount() +"      "+sellout.getCount()*sellout.getPrice()+"\r\n").getBytes("gbk"));

			}
			mOutputStream.write(("合计:                 "+total+"\r\n").getBytes("gbk"));
		//}

		mOutputStream.write(("===============================\r\n")
				.getBytes("gbk"));
		mOutputStream.write(("      打印日期:"
				+ simpleDateFormat.format(new Date()) + "   \r\n ")
				.getBytes("gbk"));
		mOutputStream.write("\r\n\r\n".getBytes());

	}
	private void print() {
		System.out.println("print/...........................");
		ViewUtil.showProgressDialog(this, "正在处理...");
		new Thread() {
			public void run() {
				System.out.println("printing2222/...........................");
				// if (!shouldPrint.isChecked()) {
				if (mSerialPort != null) {
					mSendingThread = new SendingThread();
					mSendingThread.start();
				} else {
					System.out
							.println("serial is null/...........................");
				}
			}

		}.start();
		ViewUtil.cancelProgressDialog();

	}

	@Override
	protected void onDataReceived(byte[] buffer, int size) {
		// TODO Auto-generated method stub
		
	}



	
}
